package cn.flying.cloud.task.core.controller;

import javax.annotation.Resource;

import java.time.Duration;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.flying.cloud.base.common.utils.Ft;
import cn.flying.cloud.task.bo.TaskJobLogBo;
import cn.flying.cloud.task.bo.TaskStepLogBo;
import cn.flying.cloud.task.core.quartz.enums.JobExecuteStatusEnum;
import cn.flying.cloud.task.service.TaskJobLogService;
import cn.flying.cloud.task.service.TaskStepLogService;

/**
 * 定时任务执行回调处理器
 *
 * @author: admin
 * @date: 2025年03月15日 22:08
 * @version: 1.0
 */
@RestController
@RequestMapping("/job/callback")
public class JobCallbackHandler {

    @Resource
    private TaskJobLogService taskJobLogService;
    @Resource
    private TaskStepLogService taskStepLogService;

    /**
     * 接收保存定时任务执行日志
     *
     * @param data
     * @return
     */
    @PostMapping("log")
    public void log(@RequestBody String data) {
        TaskJobLogBo log = Ft.JSON.deserialize(data, TaskJobLogBo.class);
        TaskJobLogBo taskJobLog = taskJobLogService.getObjById(log.getId());
        if (taskJobLog != null) {
            taskJobLog.setJobInstId(log.getJobInstId());
            taskJobLog.setFireTime(log.getFireTime());
            taskJobLog.setEndTime(log.getEndTime());
            taskJobLog.setDuration(Duration.between(log.getFireTime(), log.getEndTime()).toMillis());
            taskJobLog.setJobStatus(log.getJobStatus());
            taskJobLog.setJobMsg(log.getJobMsg());
            taskJobLog.setJobTrace(log.getJobTrace());
            taskJobLogService.updateObj(taskJobLog);

            // 执行失败告警通知
            if (JobExecuteStatusEnum.FAIL.getCode().equals(taskJobLog.getJobStatus())) {
                // TODO
            }
        }
    }

    /**
     * 回调保存批量任务步骤日志
     *
     * @param data
     * @return
     */
    @PostMapping("/step/log")
    public void step(@RequestBody String data) {
        TaskStepLogBo log = Ft.JSON.deserialize(data, TaskStepLogBo.class);
        taskStepLogService.createObj(log);
    }
}
